package com.htfyun.factorytest;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.core.app.ActivityCompat;

import com.htfyun.factorytest.common.Constants;
import com.htfyun.factorytest.utils.ArmFreqUtils;
import com.htfyun.factorytest.utils.MemTester;

import java.lang.ref.WeakReference;

public class MemoryTestActivity extends SingleTestBaseActivity implements View.OnClickListener {
    private MyHandler handler;
    private TextView txtLog;
    private Context mContext;
    private Thread memoryTestThread = null;
    private int testMB = 64, testCount = 1;
    private EditText editMB, editCount;
    private Button btnStart,btnQuit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_memory_test);
        handler = new MyHandler(this);
        mContext = this;

        editMB = findViewById(R.id.editMB);
        editCount = findViewById(R.id.editCount);

        txtLog = findViewById(R.id.txtLog);
        btnStart = findViewById(R.id.btnStart);
        btnQuit = findViewById(R.id.btnExit);

        btnStart.setOnClickListener(this);
        btnQuit.setOnClickListener(this);
        findViewById(R.id.btnStop).setOnClickListener(this);

        editMB.setSelection(editMB.getText().length());
        ArmFreqUtils.setCpuFreqMax();
    }

    private void startTestMemory() {
/*        ActivityManager activityManager = (ActivityManager) getContext().getSystemService(Context.ACTIVITY_SERVICE);
        DebugLog.e("getMemoryClass = " + activityManager.getMemoryClass()
                + ",getLargeMemoryClass = " + activityManager.getLargeMemoryClass());*/
        CharSequence defaultMB = editMB.getText();
        CharSequence defaultCount = editCount.getText();
        if (!TextUtils.isEmpty(defaultMB) && TextUtils.isDigitsOnly(defaultMB)) {
            testMB = Integer.parseInt(defaultMB.toString());
        }
        if (!TextUtils.isEmpty(defaultCount) && TextUtils.isDigitsOnly(defaultCount)) {
            testCount = Integer.parseInt(defaultCount.toString());
        }
        memoryTestThread = new Thread(memoryRunnable);
        memoryTestThread.start();
    }

    private void stopTestMemory() {
        if (memoryTestThread != null) {
            memoryTestThread.interrupt();
        }
    }

    private void updateLog(String log) {
        handler.obtainMessage(MyHandler.MSG_UPDATE_LOG, log).sendToTarget();
    }

    private void doUpdateLog(String log) {
        String txt = txtLog.getText().toString();
        if (txt.length() > 1024 * 6) {
            txtLog.setText(log);
        } else {
            txtLog.setText(txt + "\n" + log);
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.btnStart:
                txtLog.setText("start test Memory");
                btnStart.setEnabled(false);
                startTestMemory();
                break;
            case R.id.btnStop:
                stopTestMemory();
                break;
            case R.id.btnExit:
                stopTestMemory();
                setResult(RESULT_OK);
                ActivityCompat.finishAfterTransition(this);
                break;
        }

    }

    private static class MyHandler extends Handler {


        public static final int MSG_UPDATE_LOG = 100;
        private final WeakReference<MemoryTestActivity> activityWeakReference;

        private MyHandler(MemoryTestActivity activity) {
            super(Looper.getMainLooper());

            activityWeakReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            //弱引用会在下一次gc时回收
            MemoryTestActivity activity = activityWeakReference.get();
            if (activity == null) {
                return;
            }

            switch (msg.what) {
                case MSG_UPDATE_LOG:
                    activity.btnStart.setEnabled(true);
                    activity.doUpdateLog((String) msg.obj);
                    break;
                default:
                    break;
            }

        }
    }

    private Runnable memoryRunnable = () -> {
        try {
            int result;
            result = MemTester.memtest(testMB + "M", 1);
            if (result != Constants.EXIT_OK) {
                updateLog("memory test fail, result = " + result);
//                int count = AgingTestItemAttr.getMemoryErrorCount(mContext);
//                AgingTestItemAttr.setMemoryErrorCount(mContext, ++count);
            } else {
                updateLog("memory test ok");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    };

}
